<template>
  <div class="dashboard-view">
    <header class="dashboard-header">
      <h1 class="glow">销售数据看板</h1>
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <span class="icon">🔄</span>
          刷新数据
        </button>
      </div>
    </header>

    <div class="dashboard-content">
      <div class="cards-grid">
        <!-- 销售概览 -->
        <DataCard v-if="salesData" title="销售概览" icon="💰" class="card-full">
          <div class="overview-grid">
            <div class="overview-item">
              <div class="value">¥{{ (salesData.totalRevenue / 10000).toFixed(1) }}万</div>
              <div class="label">总收入</div>
            </div>
            <div class="overview-item">
              <div class="value">{{ salesData.totalContracts }}</div>
              <div class="label">总合同数</div>
            </div>
            <div class="overview-item">
              <div class="value">{{ salesData.activeProjects }}</div>
              <div class="label">活跃项目</div>
            </div>
            <div class="overview-item">
              <div class="value">{{ salesData.completionRate.toFixed(1) }}%</div>
              <div class="label">完成率</div>
            </div>
          </div>
        </DataCard>

        <!-- 合同状态分布 - 饼图 -->
        <DataCard v-if="contracts.length > 0" title="合同状态分布" icon="📊">
          <PieChart :data="contractStatusData" />
        </DataCard>

        <!-- 月度收入趋势 - 折线图 -->
        <DataCard v-if="salesData" title="月度收入趋势" icon="📈">
          <LineChart :data="monthlyRevenueData" title="收入" color="#00f3ff" />
        </DataCard>

        <!-- 项目状态分布 - 饼图 -->
        <DataCard v-if="projects.length > 0" title="项目状态分布" icon="📋">
          <PieChart :data="projectStatusData" />
        </DataCard>

        <!-- 合同金额排行 - 条形图 -->
        <DataCard v-if="contracts.length > 0" title="合同金额排行 TOP 10" icon="💵">
          <BarChart :data="topContractsData" title="金额(万)" color="#ff00ff" />
        </DataCard>

        <!-- 月度合同数量 - 条形图 -->
        <DataCard v-if="salesData" title="月度合同数量" icon="📄">
          <BarChart :data="monthlyContractsData" title="合同数" color="#00ff88" />
        </DataCard>

        <!-- 项目风险等级 - 饼图 -->
        <DataCard v-if="projects.length > 0" title="项目风险等级" icon="⚠️">
          <PieChart :data="projectRiskData" />
        </DataCard>

        <!-- 销售业绩排行 - 条形图 -->
        <DataCard v-if="salesData" title="销售业绩排行 TOP 5" icon="🏆">
          <BarChart :data="topPerformersData" title="业绩(万)" color="#ffaa00" />
        </DataCard>

        <!-- 项目跟踪 -->
        <ProjectTracker
          v-if="projects.length > 0"
          :projects="projects.slice(0, 8)"
          :highlight-risks="true"
          sort-by="status"
          class="card-full"
        />
      </div>
      
      <p v-if="loading" class="loading-text">加载中...</p>
      <p v-if="error" class="error-text">错误: {{ error.message }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useDashboardStore } from '@/stores/dashboard'
import DataCard from '@/components/DataCard.vue'
import ProjectTracker from '@/components/ProjectTracker.vue'
import PieChart from '@/components/PieChart.vue'
import BarChart from '@/components/BarChart.vue'
import LineChart from '@/components/LineChart.vue'

const store = useDashboardStore()
const { salesData, contracts, projects, loading, error } = storeToRefs(store)

// 合同状态分布数据
const contractStatusData = computed(() => {
  if (!contracts.value.length) return []
  const statusCount = {
    active: contracts.value.filter(c => c.status === 'active').length,
    pending: contracts.value.filter(c => c.status === 'pending').length,
    completed: contracts.value.filter(c => c.status === 'completed').length,
    cancelled: contracts.value.filter(c => c.status === 'cancelled').length
  }
  return [
    { label: '活跃', value: statusCount.active, color: '#00ff88' },
    { label: '待定', value: statusCount.pending, color: '#ffaa00' },
    { label: '完成', value: statusCount.completed, color: '#00f3ff' },
    { label: '取消', value: statusCount.cancelled, color: '#ff3366' }
  ].filter(d => d.value > 0)
})

// 项目状态分布数据
const projectStatusData = computed(() => {
  if (!projects.value.length) return []
  const statusCount = {
    planning: projects.value.filter(p => p.status === 'planning').length,
    'in-progress': projects.value.filter(p => p.status === 'in-progress').length,
    delayed: projects.value.filter(p => p.status === 'delayed').length,
    completed: projects.value.filter(p => p.status === 'completed').length
  }
  return [
    { label: '计划中', value: statusCount.planning, color: '#00f3ff' },
    { label: '进行中', value: statusCount['in-progress'], color: '#00ff88' },
    { label: '延期', value: statusCount.delayed, color: '#ffaa00' },
    { label: '已完成', value: statusCount.completed, color: '#8892b0' }
  ].filter(d => d.value > 0)
})

// 项目风险等级数据
const projectRiskData = computed(() => {
  if (!projects.value.length) return []
  const riskCount = {
    low: projects.value.filter(p => p.riskLevel === 'low').length,
    medium: projects.value.filter(p => p.riskLevel === 'medium').length,
    high: projects.value.filter(p => p.riskLevel === 'high').length
  }
  return [
    { label: '低风险', value: riskCount.low, color: '#00ff88' },
    { label: '中风险', value: riskCount.medium, color: '#ffaa00' },
    { label: '高风险', value: riskCount.high, color: '#ff3366' }
  ].filter(d => d.value > 0)
})

// 月度收入趋势数据
const monthlyRevenueData = computed(() => {
  if (!salesData.value) return []
  return salesData.value.monthlyTrend.map(m => ({
    label: m.month,
    value: Math.round(m.revenue / 10000)
  }))
})

// 月度合同数量数据
const monthlyContractsData = computed(() => {
  if (!salesData.value) return []
  return salesData.value.monthlyTrend.map(m => ({
    label: m.month,
    value: m.contracts
  }))
})

// 合同金额排行数据
const topContractsData = computed(() => {
  if (!contracts.value.length) return []
  return contracts.value
    .sort((a, b) => b.amount - a.amount)
    .slice(0, 10)
    .map(c => ({
      label: c.name.length > 10 ? c.name.substring(0, 10) + '...' : c.name,
      value: Math.round(c.amount / 10000)
    }))
})

// 销售业绩排行数据
const topPerformersData = computed(() => {
  if (!salesData.value) return []
  return salesData.value.topPerformers.slice(0, 5).map(p => ({
    label: p.name,
    value: Math.round(p.revenue / 10000)
  }))
})

async function refreshData() {
  await store.refreshData()
}

onMounted(async () => {
  console.log('DashboardView mounted')
  try {
    await store.fetchDashboardData()
    console.log('Data fetched:', salesData.value)
  } catch (err) {
    console.error('Error fetching data:', err)
  }
})
</script>

<style lang="scss" scoped>
.dashboard-view {
  min-height: 100vh;
  background: var(--bg-primary);
  color: var(--text-primary);
}

.dashboard-header {
  padding: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  
  h1 {
    font-size: 2rem;
    margin: 0;
    color: var(--color-primary);
    text-shadow: 0 0 20px var(--color-primary);
  }
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background: var(--color-primary);
  color: var(--bg-primary);
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 0 10px var(--color-primary);
  
  &:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 0 20px var(--color-primary);
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.dashboard-content {
  padding: 2rem;
  max-width: 1600px;
  margin: 0 auto;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 2rem;
  
  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
}

.card-full {
  grid-column: 1 / -1;
}

.overview-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.overview-item {
  text-align: center;
  padding: 1.5rem;
  background: rgba(0, 243, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(0, 243, 255, 0.2);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-4px);
    border-color: var(--color-primary);
    box-shadow: 0 0 20px rgba(0, 243, 255, 0.3);
  }
  
  .value {
    font-size: 2rem;
    font-weight: bold;
    color: var(--color-primary);
    margin-bottom: 0.5rem;
    text-shadow: 0 0 10px var(--color-primary);
  }
  
  .label {
    font-size: 0.875rem;
    color: var(--text-secondary);
  }
}

.loading-text, .error-text {
  text-align: center;
  padding: 2rem;
  font-size: 1.1rem;
}

.error-text {
  color: #ff3366;
}
</style>
